package ex.system.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import modules.system.entity.Attach;
import modules.system.service.AttachService;

import org.apache.struts.upload.FormFile;

import com.guinea.core.Constants;
import com.guinea.core.utils.CommonUtils;

public class AttachServiceEx extends AttachService {
	public Long saveFile(FormFile formFile){
		return saveFile(formFile,null);
	}
	
	public Long saveFile(FormFile formFile,String path){
		String webPathRoot = "/attachments";
		if(path != null) webPathRoot += path;
		Attach attach = new Attach();
		attach.setStatus(Constants.STATUS_VALID);
		attach.setCreatedDate(new Date());
		attach.setCreatedUser(CommonUtils.getCurrentUserId());
		attach.setFileName(formFile.getFileName());
		attach.setFileSize(new Long(formFile.getFileSize()));
		attach.setWebPath(webPathRoot);
		save(attach);

		String physicalPath = System.getProperty("app.path")
				+ attach.getWebPath();
		String fileType = "";
		int dotIndex = formFile.getFileName().lastIndexOf(".");
		if (dotIndex > -1) {
			fileType = "." + formFile.getFileName().substring(dotIndex + 1);
		}
		attach.setWebPath(webPathRoot + "/" + attach.getId().longValue()
				+ fileType);
		save(attach);

		InputStream in = null;
		FileOutputStream out = null;
		try {
			in = formFile.getInputStream();
			File dir = new File(physicalPath);
			if (!dir.exists())
				dir.mkdirs();
			out = new FileOutputStream(physicalPath + "/"
					+ attach.getId().longValue() + fileType);
			CommonUtils.io(in, out);
		} catch (FileNotFoundException e) {
			logger.error("write attach id " + attach.getId() + " :", e);
		} catch (IOException e) {
			logger.error("write attach id " + attach.getId() + " :", e);
		}
		return attach.getId();
	}
}
